package com.gcp.freemarker.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ToolUtils {

    /**
     * 获取请求来源ip地址
     */
    public static String getIpAddr() {
        RequestAttributes requestAttribute = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttribute).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 复制非空的属性
     */
    public static void copyNonNullProperties(Object source, Object target) {
        // 获取所有字段
        List<Field> fields = getAllFields(source.getClass());
        List<Field> fieldsList = getAllFields(target.getClass());
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object value = field.get(source);
                if (value != null) {
                    Field targetField = findFieldByName(fieldsList, field.getName());
                    targetField.setAccessible(true);

                    targetField.set(target, value);
                }
            } catch (Exception e) {

            }
        }
    }

    // 获取一个类及其父类的所有字段
    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()));
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null) {
            fields.addAll(getAllFields(superClass));
        }
        return fields;
    }

    // 在字段列表中查找指定名称的字段
    private static Field findFieldByName(List<Field> fields, String name) {
        return fields.stream()
                .filter(f -> f.getName().equals(name))
                .findFirst()
                .orElse(null);
    }

    private final static List<String> ignoreFields = Arrays.asList("id");

    /**
     * 复制属性(可指定忽略参数)
     */
    public static void copyIgnoreProperties(Object source, Object target) {
        // 获取所有字段
        List<Field> fields = getAllFields(source.getClass());
        List<Field> fieldsList = getAllFields(target.getClass());
        for (Field field : fields) {
            try {
                if (ignoreFields.contains(field.getName())) {
                    continue;
                }
                field.setAccessible(true);
                Object value = field.get(source);
                if (value != null) {
                    Field targetField = findFieldByName(fieldsList, field.getName());
                    targetField.setAccessible(true);

                    targetField.set(target, value);
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 反射获取所有接口的路径和注释
     */
//    public static List<MenuInfo> extractApiEndpoints(Class<?> controllerClass, Long parentMenuId) {
//        List<MenuInfo> endpointInfos = new ArrayList<>();
//
//        // 获取类级别的 RequestMapping 注解
//        RequestMapping classRequestMapping = controllerClass.getAnnotation(RequestMapping.class);
//        String classPath = "";
//        if (classRequestMapping != null && classRequestMapping.value().length > 0) {
//            classPath = classRequestMapping.value()[0];
//        }
//        Api api = controllerClass.getAnnotation(Api.class);
//        // 遍历类中的所有方法
//        for (Method method : controllerClass.getDeclaredMethods()) {
//            // 检查是否有 ApiOperation 注解
//            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
//            if (apiOperation == null) {
//                continue; // 如果没有 ApiOperation 注解，则跳过该方法
//            }
//            MenuInfo menuInfo = new MenuInfo();
//            String description = apiOperation.value();
//
//            // 获取方法级别的路径
//            String methodPath = "";
//            if (method.isAnnotationPresent(RequestMapping.class)) {
//                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
//                if (requestMapping.value().length > 0) {
//                    methodPath = requestMapping.value()[0];
//                }
//            } else if (method.isAnnotationPresent(GetMapping.class)) {
//                GetMapping getMapping = method.getAnnotation(GetMapping.class);
//                if (getMapping.value().length > 0) {
//                    methodPath = getMapping.value()[0];
//                } else {
//                    methodPath = "";
//                }
//                menuInfo.setType(MenuTypeEnum.MENU.getCode());
//            } else if (method.isAnnotationPresent(PostMapping.class)) {
//                PostMapping postMapping = method.getAnnotation(PostMapping.class);
//                if (postMapping.value().length > 0) {
//                    methodPath = postMapping.value()[0];
//                } else {
//                    methodPath = "";
//                }
//                //按钮
//                menuInfo.setType(MenuTypeEnum.BUTTON.getCode());
//            }
//            String fullPath = classPath + methodPath;
//            // 组合完整的 URL 路径
//            menuInfo.setAlias(description);
//            menuInfo.setPerms(fullPath);
//            menuInfo.setStatus(CommonStatusEnum.enable.getCode());
//            menuInfo.setCreator(1L);
//            menuInfo.setUpdater(1L);
//            menuInfo.setVisible(CommonStatusEnum.enable.getCode());
//            menuInfo.setIcon("SettingOutlined");
//            menuInfo.setParentMenuId(parentMenuId);
//            // 创建并保存 API 信息
//            endpointInfos.add(menuInfo);
//        }
//
//        return endpointInfos;
//    }

}
